<?php
/**
 * Created by PhpStorm.
 * User: liyu
 * Date: 2018/4/9
 * Time: 上午10:07
 */

namespace app\common\exception;


use app\api\model\ErrorLog;
use think\Log;
use think\Request;

class Handle extends \think\exception\Handle
{
    public function render(\Exception $e)
    {
        header('Access-Control-Allow-Origin: *');
        if ($e instanceof Base) {
            $obj = Base::instance();
            $msg = $obj->getMsg();
            $code = $obj->getErrorCode();
        } else {
            if (config('app_debug')) {
                return parent::render($e); // TODO: Change the autogenerated stub
            } else {
                $msg = '服务器内部错误';
                $code = 99999;
                $this->recordErrorLog($e);
            }
        }
        $result = [
            'code'=>$code,
            'msg'=>$msg,
//            'request_url'=>request()->url()
        ];
        return json($result);
    }

    protected function recordErrorLog($e)
    {
        config('log.path',LOG_PATH.'exception/');
        ErrorLog::create([
            'route' => Request::instance()->url(),
            'param' => json_encode(Request::instance()->param()),
            'file' => $e->getFile(),
            'line' => $e->getLine(),
            'msg' => $e->getMessage()
        ]);
        $url = "路由:".Request::instance()->url()."\n";
        $param = "参数:".json_encode(Request::instance()->param())."\n";
        $file = "文件:".$e->getFile()."\n";
        $line = "行号:".$e->getLine()."\n";
        $message = "信息:".$e->getMessage();
        $errorMsg = $url.$param.$file.$line.$message;
        Log::record($errorMsg,'error');
        log::save();
    }
}